import java.awt.Cursor;
import java.awt.Event;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.awt.geom.RectangularShape;
import java.util.ArrayList;

import javax.swing.JPanel;

/**
 * 
 */

/**
 * @author trunghpb
 *
 */
public class MousePanel extends JPanel {
	
	private static final int SIDELENGTH = 10;
	
	private ArrayList<Rectangle2D> squares;
	private Rectangle2D current;
	
	public MousePanel() {
		squares = new ArrayList<Rectangle2D>();
		current = null;
		
		this.addMouseListener(new MouseHandler());
		this.addMouseMotionListener(new MouseMotionHandler());
	}
	
	private void add(Point2D p){
		double x = p.getX();
		double y = p.getY();
		
		current = new Rectangle2D.Double(
				x - SIDELENGTH / 2,
				y - SIDELENGTH / 2,
				SIDELENGTH,
				SIDELENGTH);
		squares.add(current);
		
		repaint();
	}
	
	public void remove(Rectangle2D s){
		if (s == null) return;
		if (s == current) current = null;
		
		squares.remove(s);
		repaint();
	}
	
	public Rectangle2D find(Point2D p){
	
		for(Rectangle2D r:squares){
			if (r.contains(p)) return r;
		}
		return null;
	}
	
	@Override
	protected void paintComponent(Graphics g) {	
		super.paintComponent(g);
		
		Graphics2D g2 = (Graphics2D) g;	
		
		for(Rectangle2D r:squares){
			g2.draw(r);			
		}
	}
	
	private class MouseHandler extends MouseAdapter{
		public void mousePressed(MouseEvent e){
			current = find(e.getPoint());
			
			if (current == null){
				add(e.getPoint());
			}
		}
		
		@Override
		public void mouseClicked(MouseEvent e) {
			current = find(e.getPoint());
			
			if ((current != null) && e.getClickCount() >=2){
				remove(current);
			}				
		}
	}
	
	private class MouseMotionHandler implements MouseMotionListener{
		
		public void mouseDragged(MouseEvent e) {
			
			if(current != null){
				int x = e.getX();
				int y = e.getY();
				
				current.setFrame(
					x - SIDELENGTH / 2,
					y - SIDELENGTH / 2,
					SIDELENGTH,
					SIDELENGTH				
						);
				
				repaint();
			}			
		}
		
		public void mouseMoved(MouseEvent e) {
		
			if(find(e.getPoint()) == null){
				setCursor(Cursor.getDefaultCursor());
			}else{
				setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));
			}
		}
	}
}
